import 'dart:convert';
import 'dart:ffi';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/service/jsonModel.dart';
import 'package:projectfluttershengyihuatong/service/jsontool.dart';

import '../request_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LaunchService extends GetxController{
  /// 单例对象
  static LaunchService? _instance;

  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  LaunchService._internal();

  /// 工厂构造方法，这里使用命名构造函数方式进行声明
  factory LaunchService.getInstance() => _getInstance();

  /// 获取单例内部方法
  static _getInstance() {
    // 只能有一个实例
    _instance ??= LaunchService._internal();
    return _instance;
  }

  LaunchConfig? config;
  Future<void> getConfig() async  {
    final manager = await SharedPreferences.getInstance();
    var value = manager.getString("launchInfo");

    if (value != null) {
      var result = jsonDecode(value);
      final baseModel = BaseModel<LaunchConfig>.fromJson(result);
      config = baseModel.data;
      update([LaunchService.appConfig]);
    }else {

    }
  }

  var isConnectNetwork = false.obs;
  @override
  void onInit() {
    // TODO: implement onInit
    subscription = Connectivity().onConnectivityChanged.listen((event) {
      switch (event){
        case ConnectivityResult.none:
          isConnectNetwork.value = false;
          break;
        default:
          isConnectNetwork.value = true;
      }

    });

    ever(isConnectNetwork, (callback){
      if (callback){
      //   当有网络的时候进行数据请求
        LaunchService.requestConfig();
      }else {
        LaunchService.getInstance().getConfig();
      }
    });


    super.onInit();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    subscription.cancle();

    super.onClose();
  }

  static String appConfig = "appconfig";
  var subscription;


  static Future<BaseModel<LaunchConfig>> requestConfig() async{
    var response = await RequestManager.getInstance().dio.get("/api/config/getConfig");
    var data = jsonEncode(response.data);

    final saveManager = await SharedPreferences.getInstance();
    await saveManager.setString(data, "launchInfo");
    final baseModel = BaseModel<LaunchConfig>.fromJson(response.data);
    LaunchService.getInstance().config = baseModel.data;
    LaunchService.getInstance().update([LaunchService.appConfig]);

    return baseModel;
  }





}
